layui.use(['jquery', 'febs', 'table', 'form', 'fileUpload', 'commonJS', 'validate'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        laydate = layui.laydate,
        commonJS = layui.commonJS,
        $view = $('#task-edit'),
        $iskeyTask = $view.find('#iskeyTask'),
        $auditOperator = $view.find('#auditOperator'),
        $remark=$view.find('#remark'),
        validate = layui.validate;
    form.verify(validate);

    initFormValue();
    initModels();
    $("#isSuccess").val('true');
    var  minPlanDate=getData(ctx +'schedule/getMinPlanDate',{taskCode:scheduleData.taskCode})

    laydate.render({
        elem: '#planStartdate',
        type: 'date',
        format: 'yyyy-MM-dd',
        btns: ['now', 'confirm'],
        trigger: 'click',
        isInitValue: true,
        min:minPlanDate,
        done: function (value, date, endDate) {
            calEndDate();
        }
    });
    form.on('select(planStarttime)', function (data) {
        calEndDate();
    });

    $('#testDay').bind('change', function () {
        calEndDate();
    })

    function calEndDate() {
        var testday = $('#testDay').val();
        var startDate = $('#planStartdate').val();
        var starttime = $('#planStarttime').val();
        if (testday == '' || startDate == '' || starttime == '') {
            return;
        }
        const date = new Date(startDate);
        var intday = parseInt(testday);
        date.setDate(date.getDate() + intday);
        var halfday = testday - intday;
        if (halfday == 0) {
            if (starttime == '09:00') {
                date.setHours(-7);
            } else if (starttime == '12:00') {
                date.setHours(12);
            }
        } else if (halfday == 0.5) {
            if (starttime == '09:00') {
                date.setHours(12);
            } else if (starttime == '12:00') {
                date.setHours(17);
            }
        }
        $('#planEnddate').html(formatDate(date));
    }

    function formatDate(date) {
        let y = date.getFullYear()
        let m = date.getMonth() + 1
        let day = date.getDate()
        let h = date.getHours();
        m = m < 10 ? '0' + m : m
        day = day < 10 ? '0' + day : day
        h = h < 10 ? '0' + h : h
        return y + '-' + m + '-' + day + ' ' + h + ':00'
    }

    // if (typeData == 'detail') {
    //     $auditOperator.css("display", 'none');
    //     document.getElementById("testDay").setAttribute("readonly", true);
    //     $("#attachfiles").css("display", "block");
    //     document.getElementById("planStartdate").disabled = true;
    //     document.getElementById("planStarttime").disabled = true;
    // }else
          debugger;
        if (typeData == 'aduit') {
        $auditOperator.css("display", 'block');
        document.getElementById("testDay").setAttribute("readonly", true);
        document.getElementById("attachfiles").setAttribute("display", "none");
        document.getElementById("planStartdate").disabled = true;
        document.getElementById("planStarttime").disabled = true;
        document.getElementById("remark").readOnly = true;
         $remark.css("border","none");
    } else {
        document.getElementById("testDay").removeAttribute("readonly");
        document.getElementById("remark").removeAttribute("readonly");
        $auditOperator.css("display", 'none');
    }

    if (useridData == scheduleData.rsDirector) {
        document.getElementById("testDay").setAttribute("readonly", true);
    }
    form.render();




    function initFormValue() {
        if (scheduleData) {
            form.val("task-edit-form", {
                "projectCode": scheduleData.projectCode,
                "projectName": scheduleData.projectName,
                "managers": scheduleData.managers,
                "managerids": scheduleData.managerids,
                "custName": scheduleData.custName,
                "contact": scheduleData.contact,
                "telephone": scheduleData.telephone,
                "taskCode": scheduleData.taskCode,
                "rsName": scheduleData.rsName,
                "rsCode": scheduleData.rsCode,
                "testDay": scheduleData.testDay,
                "status": scheduleData.status,
                "planStartdate": scheduleData.planStartdate,
                "planStarttime": scheduleData.planStarttime,
                "planEnddate": scheduleData.planEnddate,
                "planEndtime": scheduleData.planEndtime,
                "remark": scheduleData.remark,
                "rsDirector": scheduleData.rsDirector,
                "taskColor":scheduleData.taskColor,
                "isDrag":scheduleData.isDrag,
            });
        }
        //要放在form后面渲染， checkbox中根据name获取结果不正确
        if (scheduleData.iskeyTask === '1') {
            $iskeyTask.prop("checked", true);
        } else {
            $iskeyTask.prop("checked", false);
        }
        form.render('checkbox');
    }


    form.on('submit(task-edit-form-submit)', function (data) {
        if (typeData == 'aduit') {
            commitSchedule(data);
            return false;
        }

        var data = data.field;
        data.planStarttime = $('#planStarttime').val();
        if( $('#planStarttime').val()=='' ||data.planStartdate==''||data.testDay==''){
            layer.msg('请填写计划开始时间和试验工时');
            $("#isSuccess").val('false');
            return  ;
        }
        var enddate = $('#planEnddate').html();
        if (enddate.length == 16) {
            data.planEnddate = enddate.substring(0, 10);
            data.planEndtime = enddate.substring(11, 16);
        } else {
            $("#isSuccess").val('false');
            layer.msg('结束时间不能为空');
        }

        //校验
        var info = getData(ctx + 'schedule/check', data);
        if (info.length > 0) {
            layer.msg(info);
            $("#isSuccess").val('false');
            return;
        }
        febs.modal.confirm("提交提示！", "是否提交？", function (index) {
            febs.postArray(ctx + 'schedule/commit', data, function (d) {
                layer.msg("修改成功");
                layer.closeAll();
            });
        });
        return false;

    });


    function commitSchedule(data) {
        data.field.voucherId = data.field.taskCode;
        data.field.status = data.field.auditStatus;
        data.field.remark = data.field.auditRemark;
        if( data.field.status=='3'&&data.field.remark==''){
            layer.msg('审批不通过时,请说明原因');
            $("#isSuccess").val('false');
            return ;
        }
        febs.modal.confirm("保存提示！", "是否保存？", function (index) {
            febs.postArray(ctx + 'schedule/audit', data.field, function () {
                layer.closeAll();
                $('#febs-task').find('#query').trigger('click');
            });
        });
    }


    function getFileData() {
        var fileDatas = $view.find(".fileOne");
        var list = [];
        $.each(fileDatas, function (index, item) {
            var data = {
                filePath: item.dataset.filepath,
                fileName: item.dataset.filename,
                smallPath: item.dataset.smallpath,
            };
            list.push(data);
        });
        return list;
    }

    function initModels() {
        febs.table.init({
            elem: $view.find('table'),
            id: 'taskModels',
            data: scheduleData.taskModelArray,
            page: false,
            loading: false,
            even: false,
            format: 'yyyy-MM-dd HH:mm',
            height: getTableHeight() / 3,
            width:580,
            skin: '',
            cols: [[
                {field: 'id', title: 'id', minWidth: 20, hide: true},
                {field: 'typename', title: '模型', width: 30, edit: false, sort: false},
                {
                    field: 'code', title: '模型编号', width: 180, edit: false, templet: function (d) {
                        return d.code.slice(3);
                    }
                },
                {
                    field: 'demandEnddate', title: '要求完成时间', width:150, edit: false, templet: function (d) {
                           if(d.demandEnddate==undefined){
                               return  "";
                           }else{
                               return layui.util.toDateString(d.demandEnddate, "yyyy-MM-dd HH:mm");
                           }
                    }
                },
                {
                    field: 'actuallyEnddate', title: '实际完成时间', width:150, edit: false, templet: function (d) {
                         if(d.actuallyEnddate==undefined){
                             return "";
                         }else {
                             return layui.util.toDateString(d.actuallyEnddate, "yyyy-MM-dd HH:mm");
                         }
                    }
                },
            ]],
            // toolbar: '',
            defaultToolbar: [],
            done: function (res, curr, count) {
            }
        });
    }


    function getData(url, condition) {
        var result = '';
        $.ajax({
            type: "get",
            dataType: "json",
            url: url,
            data: condition,
            cache: false,
            async: false,
            success: function (data) {
                result = data.data;
            },
        });
        return result;
    }


    function getTableHeight() {
        return commonJS.calcTableHeight();
    }


});